package com.jp.knowledge.my.activity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bigkoo.quicksidebar.QuickSideBarTipsView;
import com.bigkoo.quicksidebar.QuickSideBarView;
import com.bigkoo.quicksidebar.listener.OnQuickSideBarTouchListener;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.my.adapter.ContactsAdapter;
import com.jp.knowledge.my.business.ContactsBusiness;
import com.jp.knowledge.my.business.Vector;
import com.jp.knowledge.my.model.ContactsModel;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.my.util.PinyinComparator;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 通讯录
 *
 * @author gzejia 978862664@qq.com
 */
public class ContactsActivity extends SlidingActivity {

    /**
     * 手机通讯录
     */
    public static final int CONTACTS_PHONE = 0;
    /**
     * 公司通讯录
     */
    public static final int CONTACTS_COMPANY = 2;

    private int mContactsType = CONTACTS_PHONE;

    @ViewInject(R.id.contacts_sbv)
    private QuickSideBarView mSideBarSbv;

    @ViewInject(R.id.contacts_btv)
    private QuickSideBarTipsView mSideBarBtv;

    @ViewInject(R.id.contacts_rv)
    private RecyclerView mOrganizeRv;

    @ViewInject(R.id.contacts_rly_search)
    private View mSearchV;

    @ViewInject(R.id.contacts_edit_search)
    private EditText mSearchEdt;

    @ViewInject(R.id.contacts_iv_clear)
    private ImageView mClearIv;

    @ViewInject(R.id.contacts_lly_auth)
    private View mAuthV;

    private ContactsBusiness mBusiness = new ContactsBusiness();
    private ContactsAdapter mContactsAdapter;

    // 侧边栏字母集合
    private HashMap<String, Integer> mLetters = new HashMap<>();
    // 拼音校对
    private PinyinComparator mComparator = new PinyinComparator();
    // 联系人集合
    private List<ContactsModel> mContactsModels = new ArrayList<>();

    @Override
    protected int getResourceId() {
        return R.layout.activity_contacts;
    }

    @Event(value = {R.id.contacts_iv_clear, R.id.icon_left}, type = View.OnClickListener.class)
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.contacts_iv_clear:// 清空
                mSearchEdt.setText("");
                break;
            case R.id.icon_left:// 返回
                finish();
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MyUtil.closeKeyword(this);
    }

    @Override
    protected void init() {
        initOthers();
        initTitle();
        initOrganizeRv(mContactsModels);
        updateSideBar(mContactsAdapter.mList);
    }

    private void initTitle() {
        topName.setText(mContactsType == CONTACTS_PHONE ? // 手机通讯录
                R.string.contacts_tv_title_phone : mContactsType == CONTACTS_COMPANY ? // 公司通讯录
                R.string.contacts_tv_title_company : 0);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        topDesc.setVisibility(View.GONE);
        rightIcon.setVisibility(View.GONE);
    }

    private void initOrganizeRv(final List<ContactsModel> models) {
        mOrganizeRv.setHasFixedSize(true);
        mOrganizeRv.setLayoutManager(new LinearLayoutManager(this));
        mContactsAdapter = new ContactsAdapter(this, models);

        // 添加粘性头部视图
        StickyRecyclerHeadersDecoration headersDecor =
                new StickyRecyclerHeadersDecoration(mContactsAdapter);
        mOrganizeRv.addItemDecoration(headersDecor);
        mOrganizeRv.setAdapter(mContactsAdapter);

        if (models.isEmpty()) {
            mSearchV.setVisibility(View.GONE);
            mAuthV.setVisibility(View.VISIBLE);
        } else {
            mSearchV.setVisibility(View.VISIBLE);
            mAuthV.setVisibility(View.GONE);
        }
    }

    private void initOthers() {
        mContactsType = getIntent().getIntExtra(
                Vector.TRANSFER_INTEGER + "contacts_type", CONTACTS_PHONE);
        mSearchEdt.addTextChangedListener(mTextChange);
        mSideBarSbv.setOnQuickSideBarTouchListener(mSideBarTouch);
        initContactData();
    }

    /**
     * 初始联系人列表
     */
    private void initContactData() {
        mContactsModels = mContactsType == CONTACTS_PHONE ?
                mBusiness.getContactPhone(this) : mBusiness.getContactCompany();
    }

    private void updateSideBar(List<ContactsModel> models) {
        ArrayList<String> customLetters = new ArrayList<>();
        int position = 0;
        for (int i = 0, k = models.size(); i < k; i++) {
            String letter = models.get(i).getRemark();
            //如果没有这个key则加入并把位置也加入
            if (!mLetters.containsKey(letter)) {
                mLetters.put(letter, position);
                customLetters.add(letter);
            }
            position++;
        }
        // 不自定义则默认26个字母
        mSideBarSbv.setLetters(customLetters);
    }

    /**
     * @param filter 检索关键词
     */
    private void searchOrganize(String filter) {
        initContactData();
        List<ContactsModel> models = new ArrayList<>();
        if (TextUtils.isEmpty(filter)) {
            models = mContactsModels;
        } else {
            for (ContactsModel model : mContactsModels) {
                if (model.getName().contains(filter)) {
                    models.add(model);
                }
            }
        }

        mLetters.clear();
        ArrayList<String> customLetters = new ArrayList<>();
        int position = 0;
        for (int i = 0, k = models.size(); i < k; i++) {
            String letter = models.get(i).getRemark();
            //如果没有这个key则加入并把位置也加入
            if (!mLetters.containsKey(letter)) {
                mLetters.put(letter, position);
                customLetters.add(letter);
            }
            position++;
        }
        // 不自定义则默认26个字母
        mSideBarSbv.setLetters(customLetters);

        // 按拼音对城市排序
        Collections.sort(models, mComparator);
        mContactsAdapter.updateAdapter(models);
    }

    OnQuickSideBarTouchListener mSideBarTouch = new OnQuickSideBarTouchListener() {
        @Override
        public void onLetterChanged(String letter, int position, float y) {
            mSideBarBtv.setText(letter, position, y);
            if (mLetters.containsKey(letter)) {
                mOrganizeRv.scrollToPosition(mLetters.get(letter));
            }
        }

        @Override
        public void onLetterTouching(boolean touching) {
            mSideBarBtv.setVisibility(touching ? View.VISIBLE : View.INVISIBLE);
        }
    };

    TextWatcher mTextChange = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            searchOrganize(!TextUtils.isEmpty(charSequence.toString()) ?
                    charSequence.toString() : null);
            mClearIv.setVisibility(TextUtils.isEmpty(mSearchEdt.getText().toString())
                    ? View.GONE : View.VISIBLE);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };
}
